package com.team9.fitness.service;

import com.zrdds.simpleinterface.DDSIF;
import com.zrdds.domain.DomainParticipant;
import com.zrdds.infrastructure.ReturnCode_t;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * ZRDDS测试服务
 * 展示如何使用真正的ZRDDS API进行数据发布和订阅
 * 使用真实的ZRDDS中间件，不使用模拟实现
 */
@Service
public class ZRDDSTestService {

    private static final Logger log = LoggerFactory.getLogger(ZRDDSTestService.class);

    @Autowired
    private ZRDDSManagerService zrddsManagerService;

    private final ScheduledExecutorService testScheduler = Executors.newScheduledThreadPool(1);
    private boolean testRunning = false;

    /**
     * 初始化测试服务
     */
    @PostConstruct
    public void initialize() {
        try {
            log.info("初始化ZRDDS测试服务...");
            log.info("ZRDDS自动测试已禁用，如需测试请手动调用startZRDDSTest()方法");

            // 暂时禁用自动测试，避免干扰终端信息
            // 等待ZRDDS管理器初始化完成
            /*
             * testScheduler.scheduleWithFixedDelay(() -> {
             * if (zrddsManagerService.isInitialized() && !testRunning) {
             * startZRDDSTest();
             * }
             * }, 5, 10, TimeUnit.SECONDS);
             */

        } catch (Exception e) {
            log.error("初始化ZRDDS测试服务失败", e);
        }
    }

    /**
     * 启动ZRDDS测试
     */
    private void startZRDDSTest() {
        if (testRunning) {
            return;
        }

        testRunning = true;
        log.info("开始ZRDDS功能测试...");

        try {
            // 测试1: 基本数据发布
            testBasicDataPublishing();

            // 测试2: 主题订阅
            testTopicSubscription();

            // 测试3: 数据循环测试
            testDataLoopback();

        } catch (Exception e) {
            log.error("ZRDDS测试失败", e);
        } finally {
            testRunning = false;
        }
    }

    /**
     * 测试基本数据发布功能
     * 使用真实的ZRDDS API
     */
    private void testBasicDataPublishing() {
        log.info("=== 测试基本数据发布功能 ===");

        try {
            // 测试发布到User/Action主题
            String userActionData = "{\"actionType\":\"LOGIN\",\"userId\":1001,\"username\":\"testuser\",\"timestamp\":\""
                    + System.currentTimeMillis() + "\"}";
            boolean result1 = zrddsManagerService.publishData("User/Action", userActionData);
            log.info("发布用户行为数据: {}", result1 ? "成功" : "失败");

            // 测试发布到Exercise/Data主题
            String exerciseData = "{\"actionType\":\"START_EXERCISE\",\"userId\":1001,\"exerciseType\":\"RUNNING\",\"duration\":30,\"timestamp\":\""
                    + System.currentTimeMillis() + "\"}";
            boolean result2 = zrddsManagerService.publishData("Exercise/Data", exerciseData);
            log.info("发布运动数据: {}", result2 ? "成功" : "失败");

            // 测试发布到Diet/Record主题
            String dietData = "{\"actionType\":\"ADD_FOOD\",\"userId\":1001,\"foodName\":\"苹果\",\"calories\":52,\"timestamp\":\""
                    + System.currentTimeMillis() + "\"}";
            boolean result3 = zrddsManagerService.publishData("Diet/Record", dietData);
            log.info("发布饮食记录: {}", result3 ? "成功" : "失败");

            // 测试发布到Community/Activity主题
            String communityData = "{\"actionType\":\"CREATE_POST\",\"userId\":1001,\"postId\":2001,\"title\":\"测试帖子\",\"content\":\"这是一个测试帖子\",\"timestamp\":\""
                    + System.currentTimeMillis() + "\"}";
            boolean result4 = zrddsManagerService.publishData("Community/Activity", communityData);
            log.info("发布社区活动: {}", result4 ? "成功" : "失败");

        } catch (Exception e) {
            log.error("测试基本数据发布功能失败", e);
        }
    }

    /**
     * 测试主题订阅功能
     * 使用真实的ZRDDS API
     */
    private void testTopicSubscription() {
        log.info("=== 测试主题订阅功能 ===");

        try {
            // 订阅所有主题
            boolean result1 = zrddsManagerService.subscribeTopic("User/Action");
            log.info("订阅User/Action主题: {}", result1 ? "成功" : "失败");

            boolean result2 = zrddsManagerService.subscribeTopic("Exercise/Data");
            log.info("订阅Exercise/Data主题: {}", result2 ? "成功" : "失败");

            boolean result3 = zrddsManagerService.subscribeTopic("Diet/Record");
            log.info("订阅Diet/Record主题: {}", result3 ? "成功" : "失败");

            boolean result4 = zrddsManagerService.subscribeTopic("Community/Activity");
            log.info("订阅Community/Activity主题: {}", result4 ? "成功" : "失败");

            // 获取已订阅的主题列表
            var subscribedTopics = zrddsManagerService.getSubscribedTopics();
            log.info("已订阅的主题: {}", subscribedTopics);

        } catch (Exception e) {
            log.error("测试主题订阅功能失败", e);
        }
    }

    /**
     * 测试数据循环测试
     * 使用真实的ZRDDS API
     */
    private void testDataLoopback() {
        log.info("=== 测试数据循环测试 ===");

        try {
            // 发布测试数据，验证数据能够被正确接收和处理
            String testData = "{\"testType\":\"LOOPBACK\",\"messageId\":\"" + System.currentTimeMillis()
                    + "\",\"content\":\"这是一个循环测试数据\",\"timestamp\":\"" + System.currentTimeMillis() + "\"}";

            // 发布到所有主题进行测试
            String[] topics = { "User/Action", "Exercise/Data", "Diet/Record", "Community/Activity" };

            for (String topic : topics) {
                boolean result = zrddsManagerService.publishData(topic, testData);
                log.info("循环测试发布到主题 {}: {}", topic, result ? "成功" : "失败");

                // 短暂延迟，避免数据发送过快
                Thread.sleep(100);
            }

        } catch (Exception e) {
            log.error("测试数据循环测试失败", e);
        }
    }

    /**
     * 手动启动ZRDDS测试（供外部调用）
     */
    public void startManualTest() {
        if (zrddsManagerService.isInitialized()) {
            startZRDDSTest();
        } else {
            log.warn("ZRDDS未初始化，无法启动测试");
        }
    }

    /**
     * 停止测试
     */
    public void stopTest() {
        testRunning = false;
        log.info("ZRDDS测试已停止");
    }

    /**
     * 获取测试状态
     */
    public boolean isTestRunning() {
        return testRunning;
    }

    /**
     * 销毁测试服务
     */
    @PreDestroy
    public void destroy() {
        try {
            testRunning = false;

            if (!testScheduler.isShutdown()) {
                testScheduler.shutdown();
                try {
                    if (!testScheduler.awaitTermination(5, TimeUnit.SECONDS)) {
                        testScheduler.shutdownNow();
                    }
                } catch (InterruptedException e) {
                    testScheduler.shutdownNow();
                    Thread.currentThread().interrupt();
                }
            }

            log.info("ZRDDS测试服务已清理");
        } catch (Exception e) {
            log.error("清理ZRDDS测试服务失败", e);
        }
    }
}
